package com.zyy.study.always.code5;

import lombok.SneakyThrows;

import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

public class Consumer implements Runnable {
    private Warehouse warehouse;
    private String consumerId;


    public Consumer(String consumerId, Warehouse warehouse) {
        this.consumerId = consumerId;
        this.warehouse = warehouse;
        this.warehouse.consumerMap.put(consumerId, 0);
    }

    /**
     * 获取此消费者消费产品总数
     * @return
     */
    public Integer getConsumerCount() {
        return warehouse.consumerMap.get(consumerId);
    }

    @SneakyThrows
    public void run() {
        Random random = new Random();
        String ware = warehouse.take();
        warehouse.consumerMap.put(consumerId, warehouse.consumerMap.get(consumerId) + 1);
        System.out.println("消费者:" + consumerId + "消费:" + ware + ",共消费：" + warehouse.consumerMap.get(consumerId));
        //消费后，休眠0.2～0.8秒
        Thread.sleep(random.ints(1, 2, 8).mapToObj(i -> (long) i / 10).collect(Collectors.toList()).get(0));
    }
}
